<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\BaseController;
use app\model\Sale as SaleModel;
use think\facade\Db;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Sale extends BaseController
{
    public function index()
    {
        $keyword=request()->param('keyword');

        $status=[1=>'num|desc',2=>'num|asc',3=>'page_view|desc',4=>'page_view|asc'];

       $data= SaleModel::with('product')->when($keyword,function($query) use($keyword,$status){
           foreach ($status as $k=>$v){
               if($k==$keyword){
                   $query->order(explode('|',$v)[0],explode('|',$v)[1]);
               }
           }
       })->order('id','asc')->paginate(10);
       return $this->success($data);
    }

    public function excel()
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $sheet->setCellValue('A1', '產品名');
        $sheet->setCellValue('B1', '價格');
        $sheet->setCellValue('C1', '瀏覽量');
        $sheet->setCellValue('D1', '銷量');
        $sheet->setCellValue('E1', '銷售額');
        $sheet->setCellValue('F1', '庫存');

        //设置宽度
        $sheet->getColumnDimension('A')->setWidth(20);

        // 设置表格数据
        $data=SaleModel::with('product')->select()->toArray();
        $row = 2;

        foreach ($data as $item) {

            $sheet->setCellValue('A' . $row, $item['product']['name']);
            $sheet->setCellValue('B' . $row, $item['product']['price']);
            $sheet->setCellValue('C' . $row, $item['page_view']);
            $sheet->setCellValue('D' . $row, $item['num']);
            $sheet->setCellValue('E' . $row, $item['sale']);
            $sheet->setCellValue('F' . $row, $item['product']['num']);
            $row++;
        }
        // 输出 Excel 文件
//        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        header('Content-Disposition: attachment;filename="demo.xlsx"');
//        header('Cache-Control: max-age=0');
//        $writer->save('php://output');
//        exit;
        $filename = './uploads/數據分析.xlsx';
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save($filename);
       return $this->success(ossUpload($filename)) ;
    }

    public function delete($id)
    {
        SaleModel::where('id',$id)->delete();
        return $this->success();
    }
}
